package com.zeekr.orm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zeekr.orm.annotation.AuthCheck;
import com.zeekr.orm.common.BaseResponse;
import com.zeekr.orm.common.DeleteRequest;
import com.zeekr.orm.common.ErrorCode;
import com.zeekr.orm.common.ResultUtils;
import com.zeekr.orm.constant.UserConstant;
import com.zeekr.orm.exception.ThrowUtils;
import com.zeekr.orm.model.dto.user.UserAddRequest;
import com.zeekr.orm.model.dto.user.UserLoginRequest;
import com.zeekr.orm.model.dto.user.UserQueryRequest;
import com.zeekr.orm.model.dto.user.UserUpdateRequest;
import com.zeekr.orm.model.entity.User;
import com.zeekr.orm.model.vo.LoginUserVO;
import com.zeekr.orm.model.vo.UserVO;
import com.zeekr.orm.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.zeekr.orm.service.impl.UserServiceImpl.SALT;

/**
 * @author 吴文杰
 * @version 1.0
 * @since 2024/7/10 23:26
 */
@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  ThreadPoolExecutor getThreadPoor;

  @Autowired
  ThreadPoolExecutor postThreadPoor;

  @Autowired
  UserServiceImpl userService;


  @PostMapping("/login")
  public BaseResponse<LoginUserVO> login(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request) {
    ThrowUtils.throwIf(loginRequest == null, ErrorCode.PARAMS_ERROR);
    String userAccount = loginRequest.getUserAccount();
    String userPassword = loginRequest.getUserPassword();
    ThrowUtils.throwIf(StringUtils.isAnyBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR);
    LoginUserVO loginUserVO = userService.userLogin(userAccount,userPassword,request);
    return ResultUtils.success(loginUserVO);
  }

  @PostMapping("/add")
  public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
    ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
    User user = new User();
    BeanUtils.copyProperties(userAddRequest, user);
    String defaultPassword = "12345678";
    String password = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
    user.setUserpassword(password);
    boolean result = userService.save(user);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    return ResultUtils.success(user.getId());
  }

  @PostMapping("/update")
  public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
    ThrowUtils.throwIf(userUpdateRequest == null, ErrorCode.PARAMS_ERROR);
    User user = new User();
    BeanUtils.copyProperties(userUpdateRequest, user);
    boolean result = userService.updateById(user);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    return ResultUtils.success(true);
  }

  @PostMapping("/delete")
  public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
    ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null, ErrorCode.PARAMS_ERROR);
    boolean result = userService.removeById(deleteRequest.getId());
    return ResultUtils.success(result);
  }

  @PostMapping("/get")
  @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
  public BaseResponse<User> getUserById(long id) {
    ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
    User user = userService.getById(id);
    ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
    return ResultUtils.success(user);
  }

  @PostMapping("/get/vo")
  public BaseResponse<UserVO> getUserVOById(long id) {
    ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
    User user = getUserById(id).getData();
    return ResultUtils.success(userService.getUserVO(user));
  }

  @PostMapping("/list/page")
  public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
    int current = userQueryRequest.getCurrent();
    int size = userQueryRequest.getPageSize();
    Page<User> page = userService.page(new Page<>(current, size), userService.getQueryWrapper(userQueryRequest));
    return ResultUtils.success(page);
  }

  @PostMapping("/list/page/vo")
  public BaseResponse<List<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
    Page<User> userPage = listUserByPage(userQueryRequest).getData();
    List<UserVO> userVOList = userService.getUserVO(userPage.getRecords());
    return ResultUtils.success(userVOList);
  }


  @PostMapping("/get/page")
  @Deprecated
  public BaseResponse<Page<UserVO>> test3(@RequestBody UserQueryRequest userQueryRequest) {
    User userQuery = new User();
    userQuery.setUserrole("user");

    QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
    Page<User> page = userService.page(new Page<>(), queryWrapper).addOrder(OrderItem.desc("isDelete"));


    List<UserVO> userVOList = page.getRecords().stream().map(user -> {
      UserVO userVO = new UserVO();
      BeanUtils.copyProperties(user, userVO);
      return userVO;
    }).collect(Collectors.toList());


    Page<UserVO> userVOPage = new PageDTO<>(page.getCurrent(), page.getSize(), page.getTotal());


    userVOPage.setRecords(userVOList);
    return ResultUtils.success(userVOPage);
  }

  @GetMapping("/")
  @Deprecated
  public BaseResponse<String> test2() {

    CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
      System.out.println("任务来了" + Thread.currentThread().getName());
      try {
        Thread.sleep(30000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("任务结束" + Thread.currentThread().getName());
    }, postThreadPoor);
    return ResultUtils.success("asd");
  }

  @ApiImplicitParam(name = "id", value = "用户ID", defaultValue = "5", required = true)
  @GetMapping("/{id}")
  @Deprecated
  public BaseResponse<Object> test(@PathVariable("id") int ss) throws ExecutionException, InterruptedException {

    // ThrowUtils.throwIf(ss<1, ErrorCode.NO_AUTH_ERROR);
    CompletableFuture.supplyAsync(() -> {
      System.out.println("任务来了" + Thread.currentThread().getName());
      System.out.println(ss);
      try {
        Thread.sleep(30000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("任务结束" + Thread.currentThread().getName());
      return 5;
    }, getThreadPoor);
    return ResultUtils.success(5);
  }

}
